<?php
declare (strict_types=1);

namespace app\common\model;

class Relation extends Base
{
    protected $name = 'user_relation';

    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo,parent_id,is_active,active_type,active_sort,level_id,push_num,team_num,my_total,team_total')
            ->with(['level']);
    }

    protected function fresh(): object
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,nickname,mobile,photo,parent_id,is_active,active_type,active_sort,level_id,push_num,team_num,my_total,team_total')
            ->with(['level']);
    }

    public static function generate($new_uid, $parent_id): bool
    {
        try {
            parent::create([
                'uid' => $parent_id,
                'algebra' => 1,
                'new_uid' => $new_uid
            ]);
            $time = time();
            parent::where('new_uid', $parent_id)
                ->field('uid,algebra + 1 as algebra,"' . $new_uid . '" as new_uid,"' . $time . '" as create_time,"' . $time . '" as update_time')
                ->selectInsert([
                    'uid',
                    'algebra',
                    'new_uid',
                    'create_time',
                    'update_time'
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {

            return false;
        }
    }

    public static function renew($uid, $parent_code, $admin): array
    {
        parent::startTrans();
        try {
            if ($uid == 1) {
                throw new \Exception('禁止修改');
            }
            $user = User::where(['id' => $uid])->find();
            if ($user->code == $parent_code) {
                throw new \Exception('新推荐人不能为会员自己');
            }
            $parent = User::where(['code' => $parent_code, 'is_active' => 2])->find();
            if (!$parent) {
                throw new \Exception('新推荐人不存在或未激活');
            }
            if ($user->parent_id != $parent->id) {
                $count = parent::where(['uid' => $user->id, 'new_uid' => $parent->id])->count();
                if ($count) {
                    throw new \Exception('新推荐人不能为伞下成员');
                }
                $msg = "会员ID【{$user->id}】的推荐人ID由【{$user->parent_id}】改为【{$parent->id}】";
                //更新当前会员的信息
                $user->parent_id = $parent->id;
                $user->save();
                //删除当前会员的原推荐关系
                parent::destroy(['new_uid' => $user->id], true);
                //建立当前会员的新推荐关系
                self::generate($user->id, $user->parent_id);
                //查询伞下会员信息
                $child = parent::where(['uid' => $user->id])->order('new_uid asc')->select();
                foreach ($child as $val) {
                    //删除伞下会员的原推荐关系
                    parent::destroy(['new_uid' => $val->fresh->id], true);
                    //建立伞下会员的新推荐关系
                    self::generate($val->fresh->id, $val->fresh->parent_id);
                }
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }
            parent::commit();

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 更新团队信息
     */
    public static function renewTeamTotal($uid, $data = [['fx' => '+', 'field' => 'team_num', 'num' => 1]]): bool
    {
        try {
            if ($data) {
                $all_id = parent::where('new_uid', $uid)->column('uid');
                if (!empty($all_id)) {
                    $that = User::whereIn('id', $all_id);
                    foreach ($data as $item) {
                        if ($item['fx'] == '+') {
                            $that->inc($item['field'], floatval($item['num']));
                        } else {
                            $that->dec($item['field'], floatval($item['num']));
                        }
                    }
                    $that->save();
                }
            }

            return true;
        } catch (\Exception $e) {

            return false;
        }
    }
}